import path from 'path';

import { defineConfig } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';

export default defineConfig(({ mode }) => {
  if (['value', 'config', 'event', 'ds:value', 'ds:config', 'ds:event'].includes(mode)) {
    const capitalToken = mode
      .split(':')
      .map((word) => word[0].toUpperCase() + word.slice(1))
      .join('');

    const fileName = mode.replace(':', '-');
    return {
      publicDir: './.tmagic/public',
      build: {
        cssCodeSplit: false,
        sourcemap: false,
        minify: false,
        outDir: `../../public/entry/react/`,
        lib: {
          entry: `.tmagic/${fileName}-entry.ts`,
          name: `magicPreset${capitalToken}s`,
          fileName: `${fileName}`,
        },
        rollupOptions: {
          output: {
            entryFileNames: `[name].js`,
            chunkFileNames: `[name].js`,
            assetFileNames: `[name].[ext]`,
          },
        },
      },
    };
  }

  if (['page', 'playground'].includes(mode)) {
    return {
      plugins: [
        reactRefresh(),
      ],

      root: `./${mode}/`,

      publicDir: '../public',

      base: `/dist/${mode}`,

      build: {
        rollupOptions: {
          output: {
            entryFileNames: `assets/runtime-${mode}-[name].js`,
            chunkFileNames: `assets/runtime-${mode}-[name].js`,
            assetFileNames: `assets/runtime-${mode}-[name].[ext]`,
          },
        },
       outDir: path.resolve(process.cwd(), `../../public/runtime/react/${mode}`),
      },
    };
  }

  return {};
});
